package corej.review.lxf.oop.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ObjFactory {
    private static Properties config = new Properties();

    static {
        InputStream in = ObjFactory.class
                .getResourceAsStream("database-cfg.properties");
        if (in == null) {
            throw new ExceptionInInitializerError(
                    "no file:database-cfg.properties found error!");
        }

        try {
            config.load(in);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("failed to load file!");
        }
    }

    public static Object newInstance(Class className) {
        return newInstance(className.getName());
    }

    public static Object newInstance(String className) {
        Object instance = null;

        String configValue = config.getProperty(className);

        try {
            instance = Class.forName(configValue).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("failed to create instance of Database");
        }

        return instance;
    }
}